package com.it.you.service.id;

import com.it.you.common.utils.Conv;
import com.it.you.common.enums.IdCreatorPrefixEnum;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class IdCreatorService {

    @Autowired
    @Qualifier("stringRedisTemplate")
    private StringRedisTemplate stringRedisTemplate;
    private static final String ID_CREATE_HEAD = "ID";

    public Long nextValFromRedis(String id, String desc) {
        return stringRedisTemplate.opsForValue().increment(ID_CREATE_HEAD + ":" + id, 1);
    }

    /**
     * 根据枚举对象生成对应前缀的自增长编号
     *
     * @param genPrefixEnum
     * @return
     */
    public Map.Entry<Long, String> generateNo(IdCreatorPrefixEnum genPrefixEnum) {
        if (genPrefixEnum == null) {
            return null;
        }
        DateTime today = new DateTime();
        String split = StringUtils.isBlank(genPrefixEnum.getSplitStr()) ? "" : genPrefixEnum.getSplitStr();
        String digit = StringUtils.isBlank(genPrefixEnum.getDigit()) ? "%06d" : genPrefixEnum.getDigit();
        final String orderHead = genPrefixEnum.getPrefix() + split + today.toString("yyyyMMdd") + split;
        final Long seq = nextValFromRedis(orderHead, today.toString("yyyy-MM-dd") + " seq");
        final String seqStr = String.format(digit, seq);
        return new Map.Entry<Long, String>() {
            @Override
            public Long getKey() {
                return Conv.NL(today.toString("yyyyMMdd") + seqStr);
            }

            @Override
            public String getValue() {
                return (orderHead + seqStr);
            }

            @Override
            public String setValue(String value) {
                return null;
            }
        };
    }

}
